package cn.yr.clock.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.yr.clock.domain.entity.User;
import cn.yr.clock.domain.vo.AuthVo;
import cn.yr.clock.handler.CacheUserHandler;
import cn.yr.clock.handler.TokenHandler;
import cn.yr.clock.mapper.UserMapper;
import cn.yr.clock.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CacheUserHandler cacheHandler;

    @Autowired
    private TokenHandler tokenHandler;

    @Override
    public AuthVo wechatLogin(User user) {
        String uuid = user.getUuid();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("uuid", uuid);
        User userExt = userMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(userExt)) {
            user.setCreateTime(new Date());
            userMapper.insert(user);
            userExt = userMapper.selectOne(wrapper);
        } else {
            userExt.setUpdateTime(new Date());
            userExt.setAvatar(user.getAvatar());
            userExt.setUserName(user.getUserName());
            userExt.setNickName(user.getNickName());
            userMapper.updateById(userExt);
        }
        String token = tokenHandler.generateToken(userExt.getUserId());
        AuthVo authVo = new AuthVo();
        authVo.setToken(token);
        authVo.setUserInfo(userExt);
        cacheHandler.setUser(userExt);
        return authVo;

    }

    @Override
    public AuthVo camouflageLogin(Long userId) {
        User user = this.getById(userId);
        String token = tokenHandler.generateToken(userId);
        AuthVo authVo = new AuthVo();
        authVo.setToken(token);
        authVo.setUserInfo(user);
        cacheHandler.setUser(user);
        return authVo;
    }
}